package com.example.managemyself.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * AI助手工具类，提供与DeepSeek API的集成
 */
public class AIHelper {
    private static final String TAG = "AIHelper";
    
    // 默认API URL和模型
    private static final String DEFAULT_API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String DEFAULT_MODEL = "deepseek-chat";
    
    // 偏好设置键
    private static final String PREF_NAME = "ai_settings";
    private static final String KEY_API_KEY = "api_key";
    private static final String KEY_API_URL = "api_url";
    private static final String KEY_MODEL = "model";
    
    // HTTP客户端
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();
    
    /**
     * 消息回调接口
     */
    public interface AICallback {
        void onResponse(String response);
        void onError(String error);
    }
    
    /**
     * 对话消息类
     */
    public static class Message {
        private String role;
        private String content;
        
        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
        
        public JSONObject toJson() throws JSONException {
            JSONObject message = new JSONObject();
            message.put("role", role);
            message.put("content", content);
            return message;
        }
    }
    
    /**
     * 保存API密钥
     */
    public static void saveApiKey(Context context, String apiKey) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_API_KEY, apiKey).apply();
    }
    
    /**
     * 获取API密钥
     */
    public static String getApiKey(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_API_KEY, "");
    }
    
    /**
     * 保存API URL
     */
    public static void saveApiUrl(Context context, String apiUrl) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_API_URL, apiUrl).apply();
    }
    
    /**
     * 获取API URL
     */
    public static String getApiUrl(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_API_URL, DEFAULT_API_URL);
    }
    
    /**
     * 保存模型名称
     */
    public static void saveModel(Context context, String model) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_MODEL, model).apply();
    }
    
    /**
     * 获取模型名称
     */
    public static String getModel(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_MODEL, DEFAULT_MODEL);
    }
    
    /**
     * 发送消息到DeepSeek API
     */
    public static void sendMessage(Context context, List<Message> messages, AICallback callback) {
        String apiKey = getApiKey(context);
        if (apiKey.isEmpty()) {
            callback.onError("API密钥未设置。请在设置中配置您的DeepSeek API密钥。");
            return;
        }
        
        String apiUrl = getApiUrl(context);
        String model = getModel(context);
        
        try {
            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", model);
            
            JSONArray messagesArray = new JSONArray();
            for (Message message : messages) {
                messagesArray.put(message.toJson());
            }
            
            requestBody.put("messages", messagesArray);
            
            // 创建请求
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, requestBody.toString());
            
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .build();
            
            // 发送请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, "API请求失败", e);
                    callback.onError("网络错误: " + e.getMessage());
                }
                
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        if (!response.isSuccessful()) {
                            callback.onError("API错误: " + response.code() + " " + response.message());
                            return;
                        }
                        
                        String responseBody = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseBody);
                        
                        // 解析响应
                        JSONArray choices = jsonResponse.getJSONArray("choices");
                        JSONObject choice = choices.getJSONObject(0);
                        JSONObject message = choice.getJSONObject("message");
                        String content = message.getString("content");
                        
                        callback.onResponse(content);
                    } catch (JSONException e) {
                        Log.e(TAG, "解析响应失败", e);
                        callback.onError("解析响应失败: " + e.getMessage());
                    }
                }
            });
        } catch (JSONException e) {
            Log.e(TAG, "构建请求失败", e);
            callback.onError("构建请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 快速发送单条消息
     */
    public static void sendSingleMessage(Context context, String content, AICallback callback) {
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("user", content));
        sendMessage(context, messages, callback);
    }
    
    /**
     * 获取卦象解读
     */
    public static void getInterpretation(Context context, String prompt, AICallback callback) {
        sendSingleMessage(context, prompt, callback);
    }
} 